package com.zzyl.service.impl;


import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.constant.SuperConstant;
import com.zzyl.dto.RoleDto;
import com.zzyl.entity.Role;
import com.zzyl.entity.RoleResource;
import com.zzyl.mapper.RoleMapper;
import com.zzyl.mapper.RoleResourceMapper;
import com.zzyl.service.RoleService;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.vo.RoleVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private RoleResourceMapper roleResourceMapper;

    @Override
    public PageResponse<RoleVo> getByPage(RoleDto roleDto, Integer pageSize, Integer pageNum) {

        PageHelper.startPage(pageNum,pageSize);
        Page<Role> page=roleMapper.getByPage(roleDto);

        return PageResponse.of(page, RoleVo.class);
    }

    @Override
    public List<String> getCheckResourceNo(Long roleId) {
        List<String> list=roleResourceMapper.getCheckResourceNo(roleId);
        return list;
    }

    @Override
    @Transactional
    public void updateRole(RoleDto roleDto) {
        //修改本表数据
        Role role = BeanUtil.toBean(roleDto, Role.class);
        roleMapper.updateByPrimaryKeySelective(role);
        //修改中间表数据
        if(ObjectUtil.isEmpty(roleDto.getCheckedResourceNos())){
            return;
        }
        //先删除 后增加
        roleResourceMapper.deleteRoleResourceByRoleId(roleDto.getId());

        String[] checkedResourceNos = roleDto.getCheckedResourceNos();
        ArrayList<RoleResource> list = new ArrayList<>();

        for (String checkedResourceNo : checkedResourceNos) {
            RoleResource roleResource = RoleResource.builder()
                    .resourceNo(checkedResourceNo)
                    .roleId(roleDto.getId())
                    .dataState(SuperConstant.DATA_STATE_0)
                    .build();
            list.add(roleResource);
        }

        roleResourceMapper.batchInsert(list);
    }

    @Override
    @Transactional
    public void delete(Long roleId) {
        roleResourceMapper.deleteRoleResourceByRoleId(roleId);
        roleMapper.deleteByPrimaryKey(roleId);
    }

    @Override
    public void add(RoleDto roleDto) {
        Role role = BeanUtil.toBean(roleDto, Role.class);
        roleMapper.insert(role);
    }

    @Override
    public List<RoleVo> getAll() {
        List<Role> list=roleMapper.getAll();
        return  BeanUtil.copyToList(list, RoleVo.class);
    }


}
